
package com.sskj.jkzx.service.impl.amap;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sskj.jkzx.domain.entity.amap.message.AMessage;
import com.sskj.jkzx.domain.entity.amap.message.JdywtxMessage;
import com.sskj.jkzx.domain.entity.amap.message.Message;
import com.sskj.jkzx.domain.entity.amap.message.MessageQuery;
import com.sskj.jkzx.domain.entity.amap.message.YcAlertMessage;
import com.sskj.jkzx.domain.entity.amap.yc.ro.EquipmentInfoMore;
import com.sskj.jkzx.domain.entity.amap.yc.ro.ProjectInfo;
import com.sskj.jkzx.repository.amap.message.MessageQueryServiceImpl;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(value = "**/sskj/message", method = { RequestMethod.POST, RequestMethod.GET })
@Api(value = "历史消息查询", description = "历史消息查询")
public class MessageHistoryServiceImpl {

	protected final Log logger = LogFactory.getLog(MessageHistoryServiceImpl.class);

	public final static SimpleDateFormat DATA_FORMAT_YYYYMMDDHHMMSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Autowired
	MessageQueryServiceImpl messageQueryService;

	/***
	 * 全部历史消息记录查询
	 * 
	 * @return
	 */
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/all", method = RequestMethod.GET)
	@ApiOperation(value = "全部历史消息记录查询", httpMethod = "GET")
	public List<JdywtxMessage> queryAllMessage() {
		List<JdywtxMessage> result = new ArrayList<JdywtxMessage>();

		// 获取所有历史消息
		List<Message> messages = messageQueryService.findAllOrderByCreatedTime();
		for (Message message : messages) {

			JSONObject content;
			try {
				content = JSONObject.parseObject(message.getContent());
			} catch (Exception e) {
				content = null;
				logger.debug(e.getMessage());
				logger.info("无法解析的消息字符串：" + content);
			}

			if (content != null) {
				JdywtxMessage m = new JdywtxMessage();
				m.setClassName(content.getString("className"));
				m.setObjId(content.getString("objId"));
				m.setGlId(content.getString("glId"));
				m.setGlName(content.getString("glName"));
				m.setLongitude(content.getString("longitude"));
				m.setLatitude(content.getString("latitude"));
				m.setTxms(content.getString("txms"));
				m.setMsglx(message.getType());
				m.setJssj(DATA_FORMAT_YYYYMMDDHHMMSS.format(message.getCreatedTime()));
				result.add(m);
			}
		}

		logger.info("查到" + result.size() + "条历史消息记录");
		return result;
	}

	/***
	 * 全部历史消息记录查询(分页，无查询条件)
	 * 
	 * @return
	 */
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/page/all", method = RequestMethod.GET)
	@ApiOperation(value = "全部历史消息记录查询", httpMethod = "GET")
	public Map<String, Object> findAllMessageNoCriteria(@RequestParam(value = "page", defaultValue = "0") Integer page,
			@RequestParam(value = "size", defaultValue = "15") Integer size) {
		Page<Message> datas = messageQueryService.findAllMessageNoCriteria(page, size);
		List<Message> messages = datas.getContent();
		Map<String, Object> content = new HashMap<String, Object>();
		List<JdywtxMessage> resultMessages = new ArrayList<JdywtxMessage>();
		for (Message message : messages) {
			try {
				JSONObject resultJson = JSONObject.parseObject(message.getContent());
				JdywtxMessage m = new JdywtxMessage();
				m.setClassName(resultJson.getString("className"));
				m.setGlId(resultJson.getString("glId"));
				m.setGlName(resultJson.getString("glName"));
				m.setObjId(resultJson.getString("objId"));
				m.setLongitude(resultJson.getString("longitude"));
				m.setLatitude(resultJson.getString("latitude"));
				m.setTxms(resultJson.getString("txms"));
				m.setMsglx(message.getType());
				m.setJssj(DATA_FORMAT_YYYYMMDDHHMMSS.format(message.getCreatedTime()));
				resultMessages.add(m);
			} catch (Exception e) {
				logger.info(message.getContent());
			}
		}
		content.put("data", resultMessages);
		content.put("currentPage", page + 1);
		content.put("totalCount", datas.getTotalElements());
		return content;
	}

	/***
	 * 全部历史消息记录查询(分页，有查询条件)
	 * 
	 * @return
	 */
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/page/s", method = RequestMethod.GET)
	@ApiOperation(value = "全部历史消息记录查询", httpMethod = "GET")
	public Map<String, Object> findMessageCriteria(Integer page, Integer size, MessageQuery messageQuery) {
		Page<Message> datas = messageQueryService.findMessageCriteria(page, size, messageQuery);
		logger.info(messageQuery.toString());
		List<Message> messages = datas.getContent();
		Map<String, Object> content = new HashMap<String, Object>();
		List<AMessage> resultMessages = new ArrayList<>();
		for (Message message : messages) {
			try {
				JSONObject resultJson = JSONObject.parseObject(message.getContent());
				if ("JD".equals(message.getType())) {
					JdywtxMessage m = new JdywtxMessage();
					m.setClassName(resultJson.getString("className"));
					m.setGlId(resultJson.getString("glId"));
					m.setGlName(resultJson.getString("glName"));
					m.setObjId(resultJson.getString("objId"));
					m.setLongitude(resultJson.getString("longitude"));
					m.setLatitude(resultJson.getString("latitude"));
					m.setTxms(resultJson.getString("txms"));
					m.setMsglx(resultJson.getString("msglx"));
					m.setType(message.getType());
					m.setJssj(DATA_FORMAT_YYYYMMDDHHMMSS.format(message.getCreatedTime()));
					resultMessages.add(m);
				} else if ("YA".equals(message.getType()) || "RA".equals(message.getType())) {
					YcAlertMessage m = new YcAlertMessage();
					if (resultJson.getJSONObject("projectInfo") != null) {
						ProjectInfo projectInfo = JSON.parseObject(resultJson.getJSONObject("projectInfo").toJSONString(),
								ProjectInfo.class);
						if (projectInfo != null) {
							m.setGlId(projectInfo.getPcode());
							m.setGlName(projectInfo.getPname());
							m.setLongitude(projectInfo.getLngGd());
							m.setLatitude(projectInfo.getLatGd());
							m.setTxms("扬尘监测预警");

							String color = projectInfo.getColor();
							if ("1".equals(color)) {
								m.setAlertColor("green");
							} else if ("2".equals(color)) {
								m.setAlertColor("yellow");
							} else if ("3".equals(color)) {
								m.setAlertColor("red");
							} else if ("4".equals(color)) {
								m.setAlertColor("yellow");
							} else if ("5".equals(color)) {
								m.setAlertColor("red");
							} else {
								m.setAlertColor("green");
							}
							m.setColorCode(projectInfo.getColor());

						}
					}
					m.setType(message.getType());
					m.setJssj(DATA_FORMAT_YYYYMMDDHHMMSS.format(message.getCreatedTime()));

					if (resultJson.getJSONObject("esi") != null) {
						EquipmentInfoMore esi = JSON.parseObject(resultJson.getJSONObject("esi").toJSONString(),
								EquipmentInfoMore.class);
						if (esi != null) {
							m.setPl(esi.getSprinklestatus());
							m.setWp(esi.getFogcannonstatus());
							m.setPmTen(esi.getPmTen());
							m.setPmTwo(esi.getPmTwo());
						}
					}
					resultMessages.add(m);
				}
			} catch (Exception e) {
				logger.info(message.getContent());
			}
		}
		content.put("data", resultMessages);
		content.put("currentPage", page + 1);
		content.put("totalCount", datas.getTotalElements());
		return content;
	}
}
